import time
import re
import requests
import threading


headers = {
    'Referer': 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%B0%D9%B6%C8%CD%BC%C6%AC&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'
}
picture_url = "https://image.baidu.com/search/acjson"
count_url = []
for i in range(1, 10):
    print("\n第" + str(i) + "页")
    data = "?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E7%99%BE%E5%BA%A6%E5%9B%BE%E7%89%87&" \
           "cl=2" \
           "&lm=-1" \
           "&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=&copyright=&word=%E7%99%BE%E5%BA%A6%E5%9B%BE%E7%89%87&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&expermode=&force=&" \
           "pn="+str(30 * i)+"&rn=30&" \
           "gsm=1e&1581647524788="
    time.sleep(1)
    response = requests.get(picture_url+data, headers=headers)
    if i != 2:
        response_data = response.json()
        for index, image_data in enumerate(response_data["data"]):
            try:
                image_url = image_data['thumbURL']
                count_url.append(image_url)
                print(image_url)
            except:
                pass
    if i == 2:
        response_data = response.text
        image_urls = re.findall(r'"thumbURL":"(.*?)"', response_data)
        for image_url in image_urls:
            print(image_url)
        count_url += image_urls
print(len(count_url))


def download_image():
    for index, image in enumerate(count_url):
        image_data = requests.get(image, headers=headers)
        image_name = '%s.%s' % (index + 1, image.split('.')[-1])
        with open(r'C:\Users\Administrator\Pictures\百度图片\\'+image_name, 'wb') as f:
            f.write(image_data.content)


threading.Thread(target=download_image).start()

